package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 定时检查订单状态，如果超时则取消订单
     */
    @Scheduled(cron = "0 30 * * * ?")
    public void processTimeoutOrder(){
        log.info("处理超时订单,{}",LocalDateTime.now());
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
      List<Orders> ordersList = orderMapper.TimeoutOrder(status, time);
      if(ordersList != null){
          for(Orders orders : ordersList){
              orders.setStatus(Orders.CANCELLED);
              orders.setCancelReason("订单超时，自动取消");
              orders.setCancelTime(LocalDateTime.now());
              orderMapper.update(orders);
          }
      }
    }

    /**
     * 定时处理一直在派送中中订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processProgressOrder(){
        log.info("派送中订单凌晨一点自动完成,{}",LocalDateTime.now());
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        List<Orders> ordersList = orderMapper.TimeoutOrder(status, time);
        if(ordersList != null){
            for(Orders orders : ordersList){
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);

            }
        }
    }
}
